#include "Shm.hpp"
int main()
{
    key_t key = getkey();
    int shmid = createshm(key, Size);
    std::cout << "pid : " << getpid() << std::endl;
    std::cout << "server key : " << to_hex(key) << std::endl;
    std::cout << "server shmid : " << shmid << std::endl;

    char *start = (char *)shmat(shmid, NULL, 0);
    if ((void *)shmat == (void *)-1)
    {
        std::cerr << "shmat fail !!! errno : " << errno << "|" << strerror(errno) << std::endl;
        shmctl(shmid, IPC_RMID, NULL); // 即使异常，依然释放共享内存
        exit(1);
    }
    struct shmid_ds buf;
    int n = shmctl(shmid,IPC_STAT,&buf);
    if(n==-1)
    {
        std::cerr << "shmctl fail !!! errno : " << errno << "|" << strerror(errno) << std::endl;
        shmctl(shmid,IPC_RMID,0);
        exit(1);
    }
    std::cout << "================================================" << std::endl;
    std::cout << "buf.shm_cpid : " << buf.shm_cpid << std::endl;
    std::cout << "buf.shm_perm._key : " << to_hex(buf.shm_perm.__key) <<std::endl;
    int fd = open("pipetest",O_WRONLY);
    while(1) //获取客户端的信息
    {
        char buf[4];
        assert(start!=nullptr);
        read(fd,buf,sizeof(buf));
        if(strcmp(start,"quit")==0) break; //如果客户端传来的信息为quit，那么就退出
        printf("server get : %s\n",start);
        sleep(1);
        
    }
    // int cnt = 5;
    //  while (cnt) // 五秒后自动销毁共享内存
    //  {
    //      std::cout << "cnt : " << cnt << std::endl;
    //      sleep(1);
    //      cnt--;
    //  }

    // ctlshm(shmid, IPC_RMID, NULL); // 可以直接使用不需要调用外部函数
    printf("start :%p\n", start);
    sleep(5);
    shmdt(start); //去掉上面shmat关联
    shmctl(shmid, IPC_RMID, NULL); //销毁
    close(fd);
    std::cout << "释放成功" << std::endl;
    return 0;
}